package com.org.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URLDecoder;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.org.config.Configurations;
import com.org.util.FileUtil;

/**
 * 断点下载
 * 
 * @author WangXiaoPeng
 *
 */
@Controller
@RequestMapping("down")
public class DownController {
	private static int num=1;
	
	private static int startNo=1;
	private static int exceptionNo=1;
	private static int okNo=1;
	private static int refuseNo=1;
	
	
	@RequestMapping("{file}")
	private void down(HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {
		if(num>-1) {
			System.out.println("----------------------------------访问被拒，num："+num);
			System.out.println("----------------------------------被拒数量--refuseNo："+refuseNo);
			refuseNo++;
			throw new FileNotFoundException();
			//return;
		}
		num++;
		System.out.println("-------------下载开始，num："+num);
		System.out.println("----------------------------------开始数量--startNo："+startNo);
		startNo++;
		File downloadFile = getFile(request);
		long pos = FileUtil.headerSetting(downloadFile, request, response);
		ServletOutputStream os = null;
		BufferedOutputStream out = null;
		RandomAccessFile raf = null;
		byte b[] = new byte[1024];// 暂存容器
		try {
			os = response.getOutputStream();
			out = new BufferedOutputStream(os);
			raf = new RandomAccessFile(downloadFile, "r");
			raf.seek(pos);
			try {
				int n = 0;
				while ((n = raf.read(b, 0, 1024)) != -1) {
					out.write(b, 0, n);
				}
				out.flush();
				System.out.println("-------------Ok，num："+num);
				System.out.println("----------------------------------成功数量--okNo："+okNo);
				okNo++;
			} catch (IOException ie) {
				System.out.println("-------------IoException，num："+num);
				System.out.println("----------------------------------异常数量--exceptionNo："+exceptionNo);
				exceptionNo++;
				ie.printStackTrace();
			}
		} catch (Exception e) {
			System.out.println("-------------Exception,num："+num);
			System.out.println("----------------------------------异常数量--exceptionNo："+exceptionNo);
			exceptionNo++;
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
			if (raf != null) {
				try {
					raf.close();
				} catch (IOException e) {
				}
			}
		}
		num--;
		System.out.println("--完成"+num);
	}
	@RequestMapping("picFile/{file}")
	private void downimg(HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {
		File downloadFile = getFile(request);
		long pos = FileUtil.headerSetting(downloadFile, request, response);
		ServletOutputStream os = null;
		BufferedOutputStream out = null;
		RandomAccessFile raf = null;
		byte b[] = new byte[1024];// 暂存容器
		try {
			os = response.getOutputStream();
			out = new BufferedOutputStream(os);
			raf = new RandomAccessFile(downloadFile, "r");
			raf.seek(pos);
			try {
				int n = 0;
				while ((n = raf.read(b, 0, 1024)) != -1) {
					out.write(b, 0, n);
				}
				out.flush();
			} catch (IOException ie) {
			}
		} catch (Exception e) {
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
			if (raf != null) {
				try {
					raf.close();
				} catch (IOException e) {
				}
			}
		}
	}

	private File getFile(HttpServletRequest request) throws IOException {
		//C:\nginx-1.13.5\html\e9ec9f0e1d2c406daf3613fcd174b0fa.wmv
		String uriStr = request.getServletPath();;
		if (null != uriStr) {
			uriStr = URLDecoder.decode(uriStr, "UTF-8");
			uriStr=uriStr.substring(uriStr.lastIndexOf("/")+1, uriStr.length());
			if(imgLocation(uriStr)) {
				uriStr=Configurations.getFileRepository()+File.separator+"picFile"+File.separator+uriStr;
			}else {
				uriStr=Configurations.getFileRepository()+File.separator+uriStr;
			}
		}
		return new File(uriStr);
	}
	
	public  boolean imgLocation(String fileName) throws IOException {
        String reg = "(jpg|png|gif|jpeg)";
        Pattern p = Pattern.compile(reg);
        boolean boo = p.matcher(fileName.toLowerCase()).find();
       return boo;
    }
	

}
